package id.web.faisalabdillah.xtimesheet.dao.impl;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceException;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.jpa.JpaCallback;
import org.springframework.orm.jpa.JpaTemplate;
import org.springframework.stereotype.Component;

import com.google.appengine.api.datastore.Key;

import id.web.faisalabdillah.xtimesheet.dao.ITimeSheetDao;
import id.web.faisalabdillah.xtimesheet.domain.TimeSheet;

@Component
public class TimeSheetDaoImpl implements ITimeSheetDao {
	
	private JpaTemplate jpaTemplate;
	
	@Autowired
	protected void setJpaTemplate(EntityManagerFactory entityManagerFactory){
		this.jpaTemplate = new JpaTemplate(entityManagerFactory);
	}
	@Override
	public void insert(TimeSheet object) {
		jpaTemplate.persist(object);
	}

	@Override
	public void delete(TimeSheet object) {
		jpaTemplate.remove(object);
	}

	@Override
	public void update(TimeSheet object) {
		jpaTemplate.merge(object);
	}

	@Override
	public TimeSheet findById(Key id) {
		return jpaTemplate.find(TimeSheet.class, id);
	}

	@Override
	public List<TimeSheet> listAll() {
		return jpaTemplate.find("select ts from TimeSheet ts");
	}

	@Override
	public List<TimeSheet> listPaging(final int firstRow, final int maxRow) {
		return jpaTemplate.execute(new JpaCallback<List<TimeSheet>>() {

			@Override
			public List<TimeSheet> doInJpa(EntityManager arg0)
					throws PersistenceException {
				Query q=arg0.createQuery("select ts from TimeSheet ts");
				q.setFirstResult(firstRow);
				q.setMaxResults(maxRow);
				return q.getResultList();
			}
		});
	}
	/* (non-Javadoc)
	 * @see id.web.faisalabdillah.xtimesheet.dao.ITimeSheetDao#findByDate(java.util.Date)
	 */
	@Override
	public TimeSheet findByDate(final Date date) {
		return jpaTemplate.execute(new JpaCallback<TimeSheet>() {

			@Override
			public TimeSheet doInJpa(EntityManager em)
					throws PersistenceException {
				Query q=em.createQuery("select t from TimeSheet t where t.month = ?1");
				q.setParameter(1, date);
				return (TimeSheet) q.getSingleResult();
			}
		});
	}

}
